package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author : xiongke
 * @Description:
 * @Date: 2024/8/27
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Resource
    DishMapper dishMapper;
    @Resource
    DishFlavorMapper dishFlavorMapper;
    @Resource
    SetmealDishMapper setmealDishMapper;
    @Resource
    SetmealMapper setmealMapper;

    /**
     * Query 菜单页面
     *
     * @param dto DTO
     * @return {@link PageResult}
     */
    @Override
    public PageResult queryPage(DishPageQueryDTO dto) {
        //使用pageResult实现分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.queryPage(dto);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 按条件更新
     *
     * @param dish 菜
     */
    @Override
    public void updateByConditions(Dish dish) {
        dishMapper.updateByConditions(dish);
        if (dish.getStatus() == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            ArrayList<Long> ids = new ArrayList<>();
            ids.add(dish.getId());
            List<SetmealDish> setmealDishes = setmealDishMapper.queryByDishId(ids);
            if (!setmealDishes.isEmpty()) {
                for (SetmealDish setmealDish : setmealDishes) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealDish.getSetmealId())
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.updateByCondition(setmeal);
                }
            }
        }

    }

    /**
     * 按类别 ID 查询
     *
     * @param categoryId 类别 ID
     * @return {@link DishVO}
     */
    @Override
    public List<DishVO> queryByCategoryId(Long categoryId) {
        List<DishVO> dishVO = dishMapper.queryByCategoryId(categoryId);
        log.info("查询出得菜品信息，{}");
        return dishVO;
    }

    /**
     * 按 ID 查询
     *
     * @param id 身份证
     * @return {@link DishVO}
     */
    @Override
    public DishVO queryById(Long id) {
        DishVO dishVO = dishMapper.queryWithCategoryName(id);
        List<DishFlavor> dishFlavor = dishFlavorMapper.queryByDishId(id);
        dishVO.setFlavors(dishFlavor);
        return dishVO;
    }

    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.save(dish);
        //使用 @Options(useGeneratedKeys = true ,keyProperty = "id") 拿到id
        Long id = dish.getId();
        List<DishFlavor> flavors = dto.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            // 保存菜品口味
            dishFlavorMapper.save(flavors);
        }
    }

    /**
     * 删除批处理
     *
     * @param ids IDS
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {

        // 判断菜品是否处于起售状态
        //todo 需要优化
        for (Long id : ids) {
            Dish dish = dishMapper.queryById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        // 判断菜品是否被套餐关联
        List<SetmealDish> setmealDishList = setmealDishMapper.queryByDishId(ids);
        if (!setmealDishList.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.deleteBatch(ids);
        dishFlavorMapper.deleteBatch(ids);
    }

    /**
     * 更新菜品信息
     *
     * @param dto DTO
     */
    @Override
    @Transactional
    public void updateDishWithFlavor(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        dishMapper.updateByConditions(dish);
        //更新口味
        dishFlavorMapper.deleteBatch(Arrays.asList(dto.getId()));
        List<DishFlavor> flavors = dto.getFlavors();
        if (!flavors.isEmpty()) {
            Long id = dish.getId();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorMapper.save(flavors);
        }

    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.queryByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
